package com.hishop.util;

import com.hishop.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by hejie on 2018/2/6.
 */
@Slf4j
public class JsonUtil {

    private static ObjectMapper objectMapper=new ObjectMapper();
    static{
        //对象的所有字段全部列入
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.ALWAYS);
        //取消默认转换timestamp形式
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
        //忽略空Bean转json的错误
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
        //统一日期格式
        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));
        //忽略在json字符串存在，但是在java对象中不存在对应属性的情况，防止错误
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

    public static <T> String obj2String(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (IOException e) {
            log.warn("parse object to string error:",e);
            return null;
        }
    }

    public static <T> String obj2StringPretty(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (IOException e) {
            log.warn("parse object to string error:",e);
            return null;
        }
    }
    // 第一个<T>表示泛型方法
    public static <T> T string2Obj(String str, Class<T> clazz){
      if (StringUtils.isEmpty(str) || clazz == null){
         return null;
      }
        try {
            return clazz.equals(String.class) ? (T)str : objectMapper.readValue(str,clazz);
        } catch (IOException e) {
            log.warn("parse string to object error:",e);
            return null;
        }
    }

    /**
     * 复杂对象字符串转对象形式1
     * @param str
     * @param typeReference
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String str, TypeReference<T> typeReference){
        if (StringUtils.isEmpty(str) || typeReference == null){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str,typeReference));
        } catch (IOException e) {
            log.warn("parse string to object error:",e);
            return null;
        }
    }

    /**
     * 复杂对象字符串转对象形式2
     * @param str
     * @param collectionClass
     * @param elementClasses
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String str, Class<?> collectionClass, Class<?>... elementClasses){
        JavaType javaType=objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
        try {
            return objectMapper.readValue(str,javaType);
        }catch (Exception e){
            log.warn("parse string to object error:",e);
            return null;
        }
    }

    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        user.setEmail("coderyqwh@163.com");
        user.setCreateTime(new Date());
        System.out.println("user:"+user);
        log.info("第一个user:{}",JsonUtil.obj2String(user));
        log.info("第一个user格式化:{}",JsonUtil.obj2StringPretty(user));
        User user1 = JsonUtil.string2Obj(JsonUtil.obj2String(user),User.class);
        System.out.println("user2:"+user1);
        List<User> users =new ArrayList<User>();
        users.add(user);
        users.add(user1);
        List<User> users2 =JsonUtil.string2Obj(JsonUtil.obj2String(users),List.class);
        List<User> users3 =JsonUtil.string2Obj(JsonUtil.obj2String(users),List.class,User.class);
        List<User> users4 =JsonUtil.string2Obj(JsonUtil.obj2String(users), new TypeReference<List<User>>(){});
    }

}
